package com.store.service.impl;

import com.store.entity.Address;
import com.store.mapper.AddressMapper;
import com.store.service.AddressService;
import com.store.service.ex.AddressNotFoundException;
import com.store.service.ex.DeleteException;
import com.store.service.ex.InsertException;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * 收获地址业务层
 */
@DubboService(interfaceClass = AddressService.class,version = "1.0.0",timeout = 5000)
public class AddressServiceImpl implements AddressService {

    @Autowired(required = false)
    private AddressMapper addressMapper;

    /**
     * 新增收获地址
     * @param address 收获地址基本信息
     * @param uid 用户id
     * @param username 执行者
     */
    @Override
    public void addAddress(Address address, Integer uid,String username) {
        //封装数据
        address.setUid(uid);
        address.setModifiedUser(username);
        address.setCreatedUser(username);
        address.setModifiedTime(new Date());
        address.setCreatedTime(new Date());
        int rows = addressMapper.addAddress(address);
        if(rows != 1){
            throw new InsertException("新增收获地址时出现未知的异常!");
        }
    }

    /**
     * 查询目标用户的所有收获地址
     * @param uid 用户id
     * @return
     */
    @Override
    public List<Address> getAllAddress(Integer uid) {
        List<Address> addressList = addressMapper.selectAddressByUid(uid);
        if(addressList == null){
            throw new AddressNotFoundException("收获地址不存在！");
        }else {
            //过滤数据
            addressList.forEach(address -> {
                address.setCreatedUser(null);
                address.setModifiedUser(null);
                address.setCreatedTime(null);
                address.setModifiedTime(null);
            });
        }
        return addressList;
    }

    /**
     * 查询收获地址
     * @param aid 收获地址id
     * @param uid 用户id
     * @return
     */
    @Override
    public Address getAddress(Integer aid, Integer uid) {
        Address exists = addressMapper.selectAddressByAid(aid, uid);
        if(exists == null){
            throw new AddressNotFoundException("收获地址不存在！");
        }
        return exists;
    }

    /**
     * 删除收货地址
     * @param aid 收货地址id
     * @return
     */
    @Override
    public void deleteAddress(Integer aid) {
        int rows = addressMapper.deleteAddress(aid);
        if(rows != 1){
            throw new DeleteException("删除收货地址出现未知的异常！");
        }
    }
}
